package com.phynos.web.main;

import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.phynos.web.main.json.JsonResult;
import com.phynos.web.main.json.ResultCodeEnum;

public class AjaxInterceptor implements HandlerInterceptor {
	
	private static final Logger Log = Logger.getLogger(AjaxInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//检查 会话是否存在		
		HttpSession session = request.getSession(false);
		if(session == null){			
			redirectToLoginView(request,response);
			return false;
		}
		//检查 会话是否有效
		Object obj = session.getAttribute(MySessionCache.KEY_SESSION_LOGIN);
		if(obj == null || !(obj instanceof MySessionCache)){
			redirectToLoginView(request,response);
			return false;
		}
		MySessionCache sc = (MySessionCache)obj;
		if(sc.checkLogin())
			return true;
		else {
			Log.debug("登录超时！");
			redirectToLoginView(request,response);
			return false;
		}			
	}

	private Boolean redirectToLoginView(
			HttpServletRequest request,
			HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("prama", "no-cache");
		response.setHeader("cache-control", "no-cache");
		OutputStreamWriter writer = null;
		ServletOutputStream os = null;
		try {  
			os = response.getOutputStream();
			writer = new OutputStreamWriter(os, "UTF-8");
			JsonResult result = JsonResult.code(ResultCodeEnum.LOGIN_FIRST,request);
			ObjectMapper mapper = new ObjectMapper();
			String val = mapper.writeValueAsString(result);
			writer.write(val);
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			try {
				if(writer != null){
					writer.close();
				}
				if(os != null){
					os.close();
				}
			} catch (Exception e2) {
				
			}
		}  
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
					throws Exception {
		
	}
}
